package com.isoft.airportsystem.service.impl.change;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.isoft.airportsystem.common.change.Result;
import com.isoft.airportsystem.entity.change.NotificationRecord;
import com.isoft.airportsystem.entity.change.NotificationSubscription;
import com.isoft.airportsystem.entity.dao.FlightChangeEvent;
import com.isoft.airportsystem.entity.dao.NotificationSubscriptionDTO;
import com.isoft.airportsystem.entity.dao.PageQuery;
import com.isoft.airportsystem.mapper.change.NotificationRecordMapper;
import com.isoft.airportsystem.mapper.change.NotificationSubscriptionMapper;
import com.isoft.airportsystem.service.change.EmailNotificationService;
import com.isoft.airportsystem.service.change.NotificationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.List;
import java.util.UUID;

@Slf4j
@Service
public class NotificationServiceImpl implements NotificationService {  // 通知服务

    private final NotificationSubscriptionMapper subscriptionMapper;
    private final NotificationRecordMapper recordMapper;
    private final EmailNotificationService emailService;

    public NotificationServiceImpl(NotificationSubscriptionMapper subscriptionMapper,
                                   NotificationRecordMapper recordMapper,
                                   EmailNotificationService emailService) {
        this.subscriptionMapper = subscriptionMapper;
        this.recordMapper = recordMapper;
        this.emailService = emailService;
    }

    // 订阅航班变更
    @Override
    public Result<NotificationSubscription> subscribeFlightChange(NotificationSubscriptionDTO dto) {
        NotificationSubscription subscription = new NotificationSubscription();
        BeanUtils.copyProperties(dto, subscription);
        subscription.setSubscriptionId(UUID.randomUUID().toString());
        subscription.setIsActive(true);
        subscriptionMapper.insert(subscription);
        return Result.success(subscription);
    }

    // 取消订阅
    @Override
    public Result<Void> unsubscribe(String subscriptionId) {
        NotificationSubscription subscription = subscriptionMapper.selectById(subscriptionId);
        if (subscription != null) {
            subscription.setIsActive(false);
            subscriptionMapper.updateById(subscription);
        }
        return Result.success(null);
    }

    // 发送通知
    @Override
    @Async
    public void sendChangeNotification(FlightChangeEvent event) {
        List<NotificationSubscription> subscriptions = getActiveSubscriptions(event.getFlightId());
        subscriptions.forEach(subscription -> {
            if ("EMAIL".equals(subscription.getNotificationType())) {
                sendEmailNotification(subscription, event);
            }
        });
    }

    //发送邮件通知
    @Override
    public Page<NotificationRecord> getNotificationRecords(PageQuery query, String flightId, String status) {
        QueryWrapper<NotificationRecord> wrapper = new QueryWrapper<>();
        if (flightId != null && !flightId.isEmpty()) {
            wrapper.eq("flight_id", flightId);
        }
        if (status != null && !status.isEmpty()) {
            wrapper.eq("send_status", status);
        }
        wrapper.orderByDesc("send_time");
        return recordMapper.selectPage(new Page<>(query.getPageNum(), query.getPageSize()), wrapper);
    }

    // 获取有效的订阅
    private List<NotificationSubscription> getActiveSubscriptions(String flightId) {
        return subscriptionMapper.selectList(
                new QueryWrapper<NotificationSubscription>()
                        .eq("flight_id", flightId)
                        .eq("is_active", true)
        );
    }

    // 发送邮件通知
    private void sendEmailNotification(NotificationSubscription subscription,
                                       FlightChangeEvent event) {
        String subject = String.format("航班%s变更通知-%s",
                event.getFlightId(), event.getChangeType());

        String content = buildEmailContent(event);

        try {
            // 关键修复：传递subscriptionId
            emailService.sendEmailNotification(
                    subscription.getSubscriptionId(),
                    subscription.getNotificationAddress(),
                    subject,
                    content
            );
        } catch (Exception e) {
            log.error("发送邮件通知失败: {}", e.getMessage());
        }
    }

    // 发送邮件通知
    private String buildEmailContent(FlightChangeEvent event) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        return """
            尊敬的旅客：
            
            您关注的航班 %s 发生了以下变更：
            变更类型：%s
            状态：%s
            时间：%s
            
            详细信息：
            %s
            
            请及时调整您的行程安排。
            
            此致
            机场管理系统
            """.formatted(
                event.getFlightId(),
                event.getChangeType(),
                event.getStatus(),
                sdf.format(event.getEventTime()),
                event.getMessage()
        );
    }
}